from django.contrib import admin
from .models import Author, Genre, Book, BookInstance, Review, UserProfile, BorrowHistory

class BookInline(admin.TabularInline):
    model = Book
    extra = 0

class AuthorAdmin(admin.ModelAdmin):
    list_display = ('last_name', 'first_name', 'date_of_birth', 'date_of_death')
    fields = ['first_name', 'last_name', ('date_of_birth', 'date_of_death'), 'bio', 'photo']
    inlines = [BookInline]

class BooksInstanceInline(admin.TabularInline):
    model = BookInstance
    extra = 0

class ReviewInline(admin.TabularInline):
    model = Review
    extra = 0

@admin.register(Book)
class BookAdmin(admin.ModelAdmin):
    list_display = ('title', 'author', 'display_genre', 'get_average_rating', 'total_likes')
    list_filter = ('author', 'genre')
    inlines = [BooksInstanceInline, ReviewInline]

    def display_genre(self, obj):
        return ', '.join(genre.name for genre in obj.genre.all()[:3])
    
    display_genre.short_description = '类型'

@admin.register(BookInstance)
class BookInstanceAdmin(admin.ModelAdmin):
    list_display = ('book', 'status', 'borrower', 'due_back', 'id')
    list_filter = ('status', 'due_back')
    
    fieldsets = (
        (None, {
            'fields': ('book', 'imprint', 'id')
        }),
        ('可用性', {
            'fields': ('status', 'due_back', 'borrower', 'borrow_date')
        }),
    )

@admin.register(Review)
class ReviewAdmin(admin.ModelAdmin):
    list_display = ('book', 'user', 'rating', 'created_date')
    list_filter = ('rating', 'created_date')

@admin.register(UserProfile)
class UserProfileAdmin(admin.ModelAdmin):
    list_display = ('user', 'get_reading_preferences')
    
    def get_reading_preferences(self, obj):
        return ', '.join(genre.name for genre in obj.reading_preferences.all()[:3])
    
    get_reading_preferences.short_description = '阅读偏好'

@admin.register(BorrowHistory)
class BorrowHistoryAdmin(admin.ModelAdmin):
    list_display = ('borrower', 'book_instance', 'borrow_date', 'return_date')
    list_filter = ('borrow_date', 'return_date')

admin.site.register(Author, AuthorAdmin)
admin.site.register(Genre)
